package com.wn.auth;

import com.wn.ov.UserOv;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

/**
 * @BelongsProject: restful_demo
 * @BelongsPackage: com.wn.auth
 * @Author: 陈云
 * @CreateTime: 2020-10-14 11:11
 * @Description:
 */
public class JWTUtil {
    /**
     * 生成公钥和私钥
     * @param publicFilename
     * @param privateFilename
     * @param secret
     */
    public static void generateKey(String publicFilename,String privateFilename,String secret){
        try {
            RsaUtils.generateKey(publicFilename,privateFilename,secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成令牌的方法
     * @param user
     * @param privateKey
     * @param time
     * @return
     */
    public static String generateToken(UserOv user, String privateKey, Integer time){
        String token = "";
        try {
            token = Jwts.builder().claim("id", user.getId())
                    .claim("userName", user.getUserName())
                    .claim("roleId", user.getRoleId())
                    .claim("roleName", user.getRoleName())
                    .claim("roleSign", user.getRoleSign())
                    .setExpiration(DateTime.now().plusMinutes(time).toDate())
                    .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey)).compact();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * 解析令牌
     * @param token
     * @param publicKey
     * @return
     */
    public static  UserOv parserToken(String token,String publicKey){
        Claims body = null;
        UserOv user = null;
        try {
            body = Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey)).parseClaimsJws(token).getBody();
            Integer id = body.get("id", Integer.class);
            String userName = body.get("userName", String.class);
            Integer roleId = body.get("roleId", Integer.class);
            String roleSign = body.get("roleSign", String.class);
            String roleName = body.get("roleName", String.class);
            user = new UserOv();
            user.setId(id);
            user.setUserName(userName);
            user.setRoleId(roleId);
            user.setRoleSign(roleSign);
            user.setRoleName(roleName);
        } catch (Exception e) {
            e.printStackTrace();
        }
       return user;
    }

}
